<?php

declare(strict_types=1);

namespace app\common\lib\sms;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use think\facade\Log;

/**
 * 实现（implements）SmsBase的sendCode接口
 * Class AliSms
 * @package app\common\lib\sms
 */
class AliSms implements SmsBase
{

    public static function sendCode(string $phone, int $code): bool
    {
        if (empty($phone) || empty($code)) {
            return false;
        }

        AlibabaCloud::accessKeyClient(config("aliyun.access_key_id"), config("aliyun.access_key_secret"))
            ->regionId(config("aliyun.region_id"))
            ->asDefaultClient();

        $templeteParam = [
            "code" => $code
        ];

        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') //https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host(config("aliyun.host"))
                ->options([
                    'query' => [
                        'RegionId' => config("aliyun.region_id"),
                        'PhoneNumbers' => $phone,
                        'SignName' => config("aliyun.sign_name"),
                        'TemplateCode' => config("aliyun.template_code"),
                        'templateParam' => json_encode($templeteParam),
                    ],
                ])
                ->request();

            //此处根据需求和场景记录日志，比如第三方服务交互时一定要纪录日志，用于后续问题排查
            Log::info("alisms-sendCode-{$phone}result".json_encode($result->toArray()));
            //print_r($result->toArray());
        } catch (ClientException $e) {
            Log::error("alisms-sendCode-{$phone}ClientException".$e->getErrorMessage());
            return false;
        } catch (ServerException $e) {
            Log::error("alisms-sendCode-{$phone}ServerException".$e->getErrorMessage());
            return false;
        }
    }
}